<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 警告提示 -->
      <el-alert title="注意：只允许第三级分类设置相关参数！" type="warning" :closable="false" show-icon> </el-alert>
      <!-- 选择商品分类 -->
      <el-form>
        <el-form-item label="选择商品分类：">
          <el-cascader v-model="classifyValue" :options="classifyList" :props="classifyProps" @change="classifyChange()" size="small"></el-cascader>
        </el-form-item>
      </el-form>
      <!-- 参数tab栏区 -->
      <el-tabs v-model="activeClassify" @tab-click="classifyClick()">
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-col>
              <el-button type="primary" :disabled="isBtnOk" @click="manyDialogVisible = true">添加参数</el-button>
            </el-col>
          </el-row>
          <el-table stripe border :data="manyList">
            <!-- 展开列表 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="item.cat_id" v-for="(item, i) in scope.row.attr_vals" closable @close="handleClose(i, scope.row)">
                  {{ item }}
                </el-tag>
                <!-- 渲染可输入的tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列表 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" class="btn_size" @click="manyModif(scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" class="btn_size" @click="manydelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-col>
              <el-button type="primary" :disabled="isBtnOk" @click="onlyDialogVisible = true">添加属性</el-button>
            </el-col>
          </el-row>
          <el-table stripe border :data="onlyList">
            <!-- 展开列表 -->
            <el-table-column type="expand">
            <template slot-scope="scope">
                <el-tag :key="item.cat_id" v-for="(item, i) in scope.row.attr_vals" closable @close="handleClose(i, scope.row)">
                  {{ item }}
                </el-tag>
                <!-- 渲染可输入的tag标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列表 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" class="btn_size" @click="onlyModif(scope.row)">修改</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" class="btn_size" @click="onlydelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 动态参数添加对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="manyDialogVisible" width="50%" @close="manyOut()">
      <el-form :model="manyForm" :rules="manyRules" ref="manyRef" label-width="100px">
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="manyForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item label="参数描述" prop="attr_vals">
          <el-input v-model="manyForm.attr_vals" placeholder="输入用参数描述，并用逗号分隔"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="manyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addMany()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 静态属性添加对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="onlyDialogVisible" width="50%" @close="onlyOut()">
      <el-form :model="onlyForm" :rules="onlyRules" ref="onlyRef" label-width="100px">
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="onlyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onlyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOnly()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 动态参数修改对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="manyModifDialogVisible" width="50%">
      <el-form :model="manyModifForm" :rules="manyModifRules" ref="manyModifRef" label-width="100px">
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="manyModifForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item label="参数描述" prop="attr_vals">
          <el-input v-model="manyModifForm.attr_vals" placeholder="输入用参数描述，并用逗号分隔"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="manyModifDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="manyModifSubmit()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 静态属性修改对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="onlyModifDialogVisible" width="50%">
      <el-form :model="onlyModifForm" :rules="onlyModifRules" ref="onlyModifRef" label-width="100px">
        <el-form-item label="静态属性" prop="attr_name">
          <el-input v-model="onlyModifForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onlyModifDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="ModifOnlySubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      classifyProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //   商品分类信息列表
      classifyList: [],
      //   获取到三级商品的id
      classifyValue: [],
      //   参数tab栏
      activeClassify: 'many',
      // 获取到参数列表
      // 动态参数列表
      manyList: [
        {
          attr_name: ''
        }
      ],
      // 静态属性列表
      onlyList: [
        {
          attr_name: ''
        }
      ],
      // 动态参数对话框隐藏与显示
      manyDialogVisible: false,
      // 静态属性对话框隐藏与显示
      onlyDialogVisible: false,
      // 动态参数修改对话框隐藏与显示
      manyModifDialogVisible: false,
      // 静态属性修改对话框隐藏与显示
      onlyModifDialogVisible: false,
      // 动态添加参数
      manyForm: {
        attr_name: '',
        attr_vals: ''
      },
      // 动态添加参数规则
      manyRules: {
        attr_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        attr_vals: [
          { required: true, message: '请输入参数描述，并用逗号分隔', trigger: 'blur' },
          { min: 2, max: 50, message: '请输入2~50个字符，并用逗号分隔', trigger: 'blur' }
        ]
      },
      // 静态添加属性
      onlyForm: {
        attr_name: ''
      },
      // 静态添加属性规则
      onlyRules: {
        attr_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      // 动态修改参数
      manyModifForm: {
        attr_name: '',
        attr_vals: ''
      },
      // 动态修改参数规则
      manyModifRules: {
        attr_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        attr_vals: [
          { required: true, message: '请输入参数描述，并用逗号分隔', trigger: 'blur' },
          { min: 2, max: 50, message: '请输入2~50个字符，并用逗号分隔', trigger: 'blur' }
        ]
      },
      // 静态添加属性
      onlyModifForm: {
        attr_name: ''
      },
      // 静态添加属性规则
      onlyModifRules: {
        attr_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      }
    }
  },
  //   钩子函数
  created() {
    //   获取商品分类列表
    this.getGoodsClassify()
  },
  // 计算属性
  computed: {
    // 如果this.classifyValue.length不等于3 就返回一个true,否则返回false
    isBtnOk() {
      if (this.classifyValue.length !== 3) {
        return true
      }
      return false
    },
    // 获取三级商品的id值
    cataId() {
      if (this.classifyValue.length === 3) {
        return this.classifyValue[2]
      }
      return null
    },
    // 动态计算标题名称
    titleText() {
      if (this.activeClassify === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  methods: {
    //   获取商品分类列表
    async getGoodsClassify() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      //   获取数据成功将数据存储在classifyList数组中
      this.classifyList = res.data
    },
    // 控制三级商品id值
    classifyChange() {
      //   控制级联选择器，强制让其选择三级商品分类，如果不是三级商品分类就让this.classifyValue重置为0
      if (this.classifyValue.length !== 3) {
        this.classifyValue = []
        this.manyList = ''
        this.onlyList = ''
        return true
      }
      this.getClassify()
    },
    // tab切换
    classifyClick() {
      this.getClassify()
    },
    // 获取商品分类数据
    async getClassify() {
      // 选择三级商品时发送请求获取分类数据
      const { data: res } = await this.$http.get(`categories/${this.cataId}/attributes`, { params: { sel: this.activeClassify } })
      if (res.meta.status !== 200) this.$message.error('获取失败')
      // 如果this.activeClassify=many就将获取到的数据存储到this.manyList数组中,否则就存储到this.onlyList数组中
      // 将attr_vals转为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 为每一行都设置tag标签切换和tag标签双向绑定的值。
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeClassify === 'many') {
        this.manyList = res.data
      } else {
        this.onlyList = res.data
      }
      // console.log(this.parameterList)
    },
    // 获取动态修改项
    async manyModif(uid) {
      // console.log(uid)
      // 发送请求获取动态参数数据
      const { data: res } = await this.$http.get(`categories/${uid.cat_id}/attributes/${uid.attr_id}`, { attr_sel: uid.attr_sel, attr_vals: uid.attr_vals })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.manyModifForm = res.data
      this.manyModifDialogVisible = true
    },
    // 修改动态参数
    manyModifSubmit() {
      // console.log(this.manyModifForm)
      // 表单验证通过就发送修改请求
      this.$refs.manyModifRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`categories/${this.manyModifForm.cat_id}/attributes/${this.manyModifForm.attr_id}`, {
            attr_name: this.manyModifForm.attr_name,
            attr_sel: this.manyModifForm.attr_sel,
            attr_vals: this.manyModifForm.attr_vals
          })
          if (res.meta.status !== 200) this.$message.eeror('修改失败')
          // 修改成功后提醒用户修改成功，关闭对话框并刷新页面
          this.$message.success('修改成功')
          this.getClassify()
          this.manyModifDialogVisible = false
        }
      })
    },
    // 获取静态修改项
    async onlyModif(uid) {
      // console.log(uid)
      // 发送请求获取动态参数数据
      const { data: res } = await this.$http.get(`categories/${uid.cat_id}/attributes/${uid.attr_id}`, { attr_sel: uid.attr_sel })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.onlyModifForm = res.data
      this.onlyModifDialogVisible = true
    },
    // 修改静态属性
    ModifOnlySubmit() {
      // 表单验证通过就发送修改请求
      this.$refs.onlyModifRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`categories/${this.onlyModifForm.cat_id}/attributes/${this.onlyModifForm.attr_id}`, {
            attr_name: this.onlyModifForm.attr_name,
            attr_sel: this.onlyModifForm.attr_sel
          })
          if (res.meta.status !== 200) this.$message.eeror('修改失败')
          // 修改成功后提醒用户修改成功，关闭对话框并刷新页面
          this.$message.success('修改成功')
          this.getClassify()
          this.onlyModifDialogVisible = false
        }
      })
    },
    // 重置动态添加
    manyOut() {
      this.$refs.manyRef.resetFields()
    },
    // 重置静态添加
    onlyOut() {
      this.$refs.onlyRef.resetFields()
    },
    // 动态参数添加
    addMany() {
      // 通过验证之后发送请求
      if (this.manyForm.attr_vals.indexOf(',') === -1) return this.$message.error('请输入正确的内容')
      this.$refs.manyRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(`categories/${this.cataId}/attributes`, { attr_name: this.manyForm.attr_name, attr_sel: this.activeClassify, attr_vals: this.manyForm.attr_vals })
          if (res.meta.status !== 201) return this.$message.error('添加失败')
          // 成功后重新刷新页面并关闭对话框
          this.$message.success('添加成功')
          this.getClassify()
          this.manyDialogVisible = false
        }
      })
    },
    // 静态属性添加
    addOnly() {
      this.$refs.onlyRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(`categories/${this.cataId}/attributes`, { attr_name: this.onlyForm.attr_name, attr_sel: this.activeClassify })
          if (res.meta.status !== 201) return this.$message.error('添加失败')
          // 成功后重新刷新页面并关闭对话框
          this.$message.success('添加成功')
          this.getClassify()
          this.onlyDialogVisible = false
        }
      })
    },
    // 动态参数删除
    async manydelete(uid) {
      // console.log(uid)
      const manydel = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (manydel !== 'confirm') return this.$message.error('已取消删除')
      // 否则就是确定删除，发送删除请求
      const { data: res } = await this.$http.delete(`categories/${uid.cat_id}/attributes/${uid.attr_id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      // 提醒用户删除成功并刷新页面
      this.$message.success('删除成功')
      this.getClassify()
    },
    // 静态属性删除
    async onlydelete(uid) {
      const onlydel = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (onlydel !== 'confirm') return this.$message.error('已取消删除')
      // 否则就是确定删除，发送删除请求
      const { data: res } = await this.$http.delete(`categories/${uid.cat_id}/attributes/${uid.attr_id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      // 提醒用户删除成功并刷新页面
      this.$message.success('删除成功')
      this.getClassify()
    },
    // tag标签失去焦点或者按下回车键都会触发，
    handleInputConfirm(scope) {
      // 如果用户没有输入内容就让scope.inputVisible = ''
      if (scope.inputValue.trim().length === 0) {
        scope.inputValue = ''
        scope.inputVisible = false
        return true
      }
      // 否则做其他的处理
      // 将用户输入的值铺设到scope.row.attr_vals中
      scope.attr_vals.push(scope.inputValue.trim())
      // 再将scope.inputVisible = ''清空
      scope.inputValue = ''
      // 隐藏输入框
      scope.inputVisible = false
      this.saveAttrValue(scope)
    },
    async saveAttrValue(scope) {
      // 将数据保存到数据库
      const { data: res } = await this.$http.put(`categories/${scope.cat_id}/attributes/${scope.attr_id}`, {
        attr_name: scope.attr_name,
        attr_sel: scope.attr_sel,
        attr_vals: scope.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('添加失败')
      this.$message.success('有效操作')
    },
    // 显示tag按钮
    showInput(scope) {
      scope.inputVisible = true
      // 自动获取焦点
      // this.$nextTick(_ => {} 的意思就当页面重新渲染完成之后才会执行箭头里面的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag对应的可选项
    handleClose(i, scope) {
      scope.attr_vals.splice(i, 1)
      this.saveAttrValue(scope)
    }
  }
}
</script>
<style lang="less" scoped>
.el-alert {
  margin-bottom: 20px;
}
.el-tag {
  margin-left: 20px;
}
.button-new-tag {
  margin-left: 20px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 20px;
  vertical-align: bottom;
}
</style>
